package com.qifenqian.turbot.net

import android.content.Context
import com.qifenqian.turbot.module.entity.response.UploadEntity
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.widget.LoadingDialog
import io.reactivex.observers.DisposableObserver
import org.jetbrains.anko.toast
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException

/**
 * @author H
 * @createDate 2018/8/9 14:29
 * @reference
 * @updateDate
 * @description
 * @detail
 * @since
 */
private const val REQUEST_SUCCESS: Int = 0  //请求成功
private const val REQUEST_SYSTEM_FAILURE: Int = 999  //请求成功,但是系统异常

private const val CONNECT_ERROR: Int = -101
private const val CONNECT_TIMEOUT: Int = -102
private const val OTHER_ERROR: Int = -100  //请求不成功的异常
private const val UPLOAD_FILE_FAILURE: Int = -110  //请求成功,但是系统异常

abstract class NetObserver<T>(context: Context, showLoading: Boolean) : DisposableObserver<Any>() {
    private var mLoadingDialog: LoadingDialog? = null
    private var mShowLoading: Boolean = showLoading
    private var mContext: Context = context

    init {
        if (showLoading) {
            mLoadingDialog = LoadingDialog(context)
            mLoadingDialog!!.setCancelable(true)
            //点击取消的时候, 停止请求网络
            mLoadingDialog!!.setOnCancelListener {
                if (!isDisposed) {
                    dispose()
                }
            }
        }
    }

    override fun onStart() {
        if (mLoadingDialog != null && !mLoadingDialog!!.isShowing) {
            try {
                mLoadingDialog!!.show()
            } catch (e: Exception) {
                Lcat.e("e", e)
            }
        }
    }

    override fun onNext(a: Any) {
        when (a) {
            is BaseEntity<*> -> {
                when ((a as BaseEntity<*>).code) {
                    REQUEST_SUCCESS        -> {
                        onSuccess(a.msg, a.t as T)
                    }
                    REQUEST_SYSTEM_FAILURE -> {
                        mContext.toast(a.msg.toString())
                        if (mLoadingDialog != null && mLoadingDialog!!.isShowing) {
                            mLoadingDialog!!.dismiss()
                        }
                        onFailure(a.code, a.msg)
                    }
                    else                   -> {
                        onFailure(a.code, a.msg)
                        if (mLoadingDialog != null && mLoadingDialog!!.isShowing) {
                            mLoadingDialog!!.dismiss()
                        }
                    }
                }
            }
            is UploadEntity  -> {
                if (a.success) {
                    onSuccess("上传成功", a as T)
                } else {
                    onFailure(UPLOAD_FILE_FAILURE, "上传失败")
                }
            }
        }
    }

    override fun onError(e: Throwable) {
        Lcat.e("网络异常", e)
        if (mLoadingDialog != null && mLoadingDialog!!.isShowing) {
            try {
                mLoadingDialog!!.dismiss()
            } catch (e: Exception) {
                Lcat.e("e", e)
            }
        }
        when (e) {
            is HttpException          -> onFailure(e.code(), e.message())
            is ConnectException       -> onFailure(CONNECT_ERROR, "连接异常")
            is SocketTimeoutException -> onFailure(CONNECT_TIMEOUT, "请求超时")
            else                      -> onFailure(OTHER_ERROR, "错误:" + e.message)
        }
    }

    override fun onComplete() {
        if (mLoadingDialog != null && mLoadingDialog!!.isShowing) {
            mLoadingDialog!!.dismiss()
        }
    }

    abstract fun onSuccess(msg: String?, t: T?)

    abstract fun onFailure(code: Int, msg: String?)
}